package com.sdy.service.Impl;

import com.sdy.dao.mysql.ManageMenuMapper;
import com.sdy.po.Authority;
import com.sdy.po.Menu;
import com.sdy.service.MenuService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

@Service
public class MenuServiceImpl implements MenuService {

    @Resource
    ManageMenuMapper manageMenuMapper;

    /**
     * 查询所有菜单模块信息
     * @return
     */
    @Override
    public List<Menu> findAllMenu() {
        return manageMenuMapper.selectAllMenu();
    }

    /**
     * 根据权限筛选需要加载的模块信息
     * @param authority
     * @return
     */
    public List<Menu> findMenuByAuthority(Authority authority){
        LinkedHashSet<Menu> menuSet = new LinkedHashSet<>();
        for (Menu menu:manageMenuMapper.selectAllMenu()) {
            if (contrastAuthority(menu.getAuthority(),authority)){
                menuSet.add(menu);
            }
        }
        List<Menu> menuList = new ArrayList<>();
        menuList.addAll(menuSet);
        return menuList;
    }

    /**
     * 对比菜单和用户的权限，只要篇有一个是true就可以加载
     * @param a1
     * @param a2
     * @return
     */
    public Boolean contrastAuthority(Authority a1,Authority a2){
        if ((a1.getCustomer()&&a2.getCustomer()) ||
            (a1.getSalesAdmin()&&a2.getSalesAdmin()) ||
            (a1.getSystemAdmin()&&a2.getSystemAdmin()) ||
            (a1.getTechnicalAdmin()&&a2.getTechnicalAdmin())){
            return true;
        }
        return false;
    }


    /**
     * 根据传参（权限）搜索相应的菜单模块
     * @param status
     * @return
     */
    @Override
    public List<Menu> findMenuByCustomer(String status) {
        if (status.equals("*")){
            return manageMenuMapper.selectAllMenu();
        }
        //开头转大写
        if (Character.isLowerCase(status.charAt(0))){
            char[] cs=status.toCharArray();
            cs[0]-=32;
            status = String.valueOf(cs);
        }
        try {
            //java反射机制
            return (List<Menu>) manageMenuMapper.getClass().getMethod("selectMenuBy"+status,null).invoke(manageMenuMapper,null);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public Boolean insertOneMenu(Menu menu) {
        return null;
    }

    @Override
    public Boolean updateOneMenu(Menu menu) {
        return null;
    }

    @Override
    public Boolean deleteOneMenuById(Integer id) {
        return null;
    }
}
